package com.topofstack.flp.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import com.bappi.custom.activities.CustomActivity;
import com.topofstack.flp.FLPApplication;
import com.topofstack.flp.R;
import com.topofstack.flp.utils.Utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class PhotosActivity extends CustomActivity implements OnClickListener {
	private static final int GALLERY_IMAGE_REQUEST_CODE = 203001;
	private static final int CAMERA_IMAGE_REQUEST_CODE = 203002;

	private Uri imUri = null;

	Button btnTakeAPhoto;
	Button btnFromPhotoLibrary;
	Button btnMyPhotos;
	Button btnDelete;
	Button btnExport;

	FLPApplication application;

	public static int count = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_photos);

		application = ((FLPApplication) getApplication());

		btnTakeAPhoto = (Button) findViewById(R.id.btnTakeAPhoto);
		btnTakeAPhoto.setOnClickListener(this);

		btnFromPhotoLibrary = (Button) findViewById(R.id.btnFromPhotoLibrary);
		btnFromPhotoLibrary.setOnClickListener(this);

		btnMyPhotos = (Button) findViewById(R.id.btnMyPhotos);
		btnMyPhotos.setOnClickListener(this);

		btnDelete = (Button) findViewById(R.id.btnDelete);
		btnDelete.setOnClickListener(this);

		btnExport = (Button) findViewById(R.id.btnExport);
		btnExport.setOnClickListener(this);
		
//		String deviceName = android.os.Build.MANUFACTURER;
//		
//		boolean isInGallery = (Pattern.compile(
//				Pattern.quote("HTC"), Pattern.CASE_INSENSITIVE)
//				.matcher(deviceName).find())
//				|| (Pattern.compile(Pattern.quote("SAMSUNG"),
//						Pattern.CASE_INSENSITIVE).matcher(
//						deviceName).find());
//		Log.i("DREG", "isInGallery ="+isInGallery);
	}

	@Override
	public void onClick(View sender) {
		if (sender == btnTakeAPhoto) {
			// Intent cameraIntent = new
			// Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			// SimpleDateFormat sdf = new
			// SimpleDateFormat("d MMM yyyy, hh_mm_ss aaa");
			// String imageFileName = String.format("%s.jpg", sdf.format(new
			// Date()));
			// String imageFilePath =
			// application.getAssetManager().imagePathFromName(imageFileName);
			// Uri uriSavedImage = Uri.fromFile(new File(imageFilePath));
			// cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);

			ContentValues values = new ContentValues();
			values.put(MediaStore.Images.Media.TITLE, "captured");
			values.put(MediaStore.Images.Media.DESCRIPTION,
					"Image capture by camera");
//			sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
//	                 Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
			imUri = getContentResolver().insert(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imUri);
			startActivityForResult(cameraIntent, CAMERA_IMAGE_REQUEST_CODE);
		} else if (sender == btnFromPhotoLibrary) {
			Intent getImageFromGalleryIntent = new Intent(Intent.ACTION_PICK);
			getImageFromGalleryIntent.setType("image/*");
			startActivityForResult(getImageFromGalleryIntent,
					GALLERY_IMAGE_REQUEST_CODE);
		} else if (sender == btnMyPhotos) {
			Intent imageGalleryIntent = new Intent(this, GalleryActivity.class);
			imageGalleryIntent.putExtra("is_delete", false);
			imageGalleryIntent.putExtra("is_export", false);
			imageGalleryIntent.putExtra("is_video", false);
			pushIntnet(imageGalleryIntent);
//			startActivity(imageGalleryIntent);
		} else if (sender == btnDelete) {
			Intent imageGalleryIntent = new Intent(this, GalleryActivity.class);
			imageGalleryIntent.putExtra("is_delete", true);
			imageGalleryIntent.putExtra("is_export", false);
			imageGalleryIntent.putExtra("is_video", false);
			pushIntnet(imageGalleryIntent);
//			startActivity(imageGalleryIntent);
		} else if (sender == btnExport) {
			Intent imageGalleryIntent = new Intent(this, GalleryActivity.class);
			imageGalleryIntent.putExtra("is_delete", false);
			imageGalleryIntent.putExtra("is_export", true);
			imageGalleryIntent.putExtra("is_video", false);
			pushIntnet(imageGalleryIntent);
//			startActivity(imageGalleryIntent);
		}
	}

	protected final void onActivityResult(final int requestCode,
			final int resultCode, final Intent i) {
		super.onActivityResult(requestCode, resultCode, i);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case GALLERY_IMAGE_REQUEST_CODE:
				Uri imageUri = i.getData();
				try {
					String path = Utils.getRealPathFromURI(imageUri, this);

					SimpleDateFormat sdf = new SimpleDateFormat(
							"d MMM yyyy, hh_mm_ss aaa");
					String imageFileName = String.format("%s.jpg",
							sdf.format(new Date()));
					String imageFilePath = application.getAssetManager()
							.imagePathFromName(imageFileName);

					application.getAssetManager().moveFile(path, imageFilePath,
							this, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;

			case CAMERA_IMAGE_REQUEST_CODE:
				try {

					Uri imageUrix = null;
					try {
						imageUrix = i.getData();
						Log.i("DREG", "URI ="+imageUrix.toString());
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(imageUrix==null){
						imageUrix = imUri;
					}
					String ret[] = Utils.getRealPathFromURIAndID(imageUrix,getParent());

					// String ret[]=Utils.getLastImageDataAndID(imageUrix,
					// this);
					
					// Toast.makeText(this, "ID=" + ret[1], Toast.LENGTH_SHORT);
					// .show();
					// File file = Utils.convertImageUriToFile(imageUrix, this);

					File file = new File(ret[0]);
					String path = file.getAbsolutePath();
					SimpleDateFormat sdf = new SimpleDateFormat(
							"d MMM yyyy, hh_mm_ss aaa");
					String imageFileName = String.format("%s.jpg",
							sdf.format(new Date()));
					String imageFilePath = application.getAssetManager()
							.imagePathFromName(imageFileName);
					application.getAssetManager().moveFile(path, imageFilePath,
							this, false);	
					int id = Integer.parseInt(ret[1]);
					int gid = Utils.getLastGalleryImageId(getParent());
					Utils.removeImage(getParent(),id);
					File f = new File(path);
					if(f.exists()){
						f.delete();
					}
					Log.i("DREG", "IDS ="+id+","+gid);
					if(gid!=id){
						Utils.removeGalleryImage(getParent(), gid);
					}					
//					try {
//
//						String deviceName = android.os.Build.MANUFACTURER;
//						boolean isInGallery = (Pattern.compile(
//								Pattern.quote("HTC"), Pattern.CASE_INSENSITIVE)
//								.matcher(deviceName).find())
//								|| (Pattern.compile(Pattern.quote("SAMSUNG"),
//										Pattern.CASE_INSENSITIVE).matcher(
//										deviceName).find());
////						Toast.makeText(this, ManufacturingName, 10000).show();
//						if (isInGallery) {
//							int id = Utils.getLastImageId(getParent());
//							removeImage(id);
//						}
//
//					} catch (Exception e) {
//						e.printStackTrace();
//					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}

//	private void delete(int id) {
//		final String[] imageColumns = { MediaStore.Images.Media.DATA,
//				MediaStore.Images.Media.DATE_TAKEN,
//				MediaStore.Images.Media.SIZE, MediaStore.Images.Media._ID };
//		final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
//		final String imageWhere = MediaStore.Images.Media._ID + ">?";
//		final String[] imageArguments = { Integer.toString(id) };
//		Cursor imageCursor = managedQuery(
//				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
//				imageWhere, imageArguments, imageOrderBy);
//		// if (imageCursor.getCount() > 1) {
//		while (imageCursor.moveToNext()) {
//			int image_id = imageCursor.getInt(imageCursor
//					.getColumnIndex(MediaStore.Images.Media._ID));
//			String path = imageCursor.getString(imageCursor
//					.getColumnIndex(MediaStore.Images.Media.DATA));
//			Long takenTimeStamp = imageCursor.getLong(imageCursor
//					.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
//			Long size = imageCursor.getLong(imageCursor
//					.getColumnIndex(MediaStore.Images.Media.SIZE));
//			// if (path.contentEquals(capturedPath)) {
//			// Remove it
//			ContentResolver cr = getContentResolver();
//			cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//					MediaStore.Images.Media._ID + "=?",
//					new String[] { Long.toString(image_id) });
//			break;
//			// }
//			// }
//		}
//		imageCursor.close();
//	}
}
